package com.chainyoung.component_tmperson.ui.activity.debit;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.view.FixedCursorEditText;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.entity.WalletDebit;
import com.chainyoung.component_tmperson.entity.WalletRepayment;
import com.chainyoung.component_tmperson.ui.mvp.contract.WalletApplyDebitContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.WalletApplyDebitPresenter;
import com.chainyoung.component_tmperson.ui.view.CommonSelectDialog;
import com.chainyoung.component_tmperson.ui.view.RepaymentTimeRuleDialog;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;

public class WalletApplyDebitActivity extends BaseActivity<WalletApplyDebitPresenter> implements WalletApplyDebitContract.View {


    @BindView(R2.id.tv_pro_type)
    TextView tvProType;
    @BindView(R2.id.rl_select_type)
    RelativeLayout rlSelectType;
    @BindView(R2.id.txt_buy_num)
    TextView txtBuyNum;
    @BindView(R2.id.et_num)
    FixedCursorEditText etNum;
    @BindView(R2.id.tv_max_amount)
    TextView tvMaxAmount;
    @BindView(R2.id.tv_buy_all)
    TextView tvBuyAll;
    @BindView(R2.id.tv_purpose_type)
    TextView tvPurposeType;
    @BindView(R2.id.rl_select_purpose_type)
    RelativeLayout rlSelectPurposeType;
    @BindView(R2.id.tv_period_type)
    TextView tvPeriodType;
    @BindView(R2.id.rl_select_period_type)
    RelativeLayout rlSelectPeriodType;
    @BindView(R2.id.tv_repayment_type)
    TextView tvRepaymentType;
    @BindView(R2.id.rl_select_repayment_type)
    RelativeLayout rlSelectRepaymentType;
    @BindView(R2.id.txt_repayment_yime)
    TextView txtRepaymentYime;
    @BindView(R2.id.et_repayment_time)
    TextView etRepaymentTime;
    @BindView(R2.id.tv_repayment_interest)
    TextView tvRepaymentInterest;
    @BindView(R2.id.cb_protocol)
    CheckBox cbProtocol;
    @BindView(R2.id.tv_user_protocol)
    TextView tvUserProtocol;


    private List<String> purposeList = new ArrayList<>();
    private List<WalletDebit> periods = new ArrayList<>();
    private List<String> periodsTimeList = new ArrayList<>();
    private List<WalletRepayment> mData = new ArrayList<>();//还款计划
    private WalletDebit walletDebit;
    private String period_id = "";//期限id
    private String maxAmount = "0";//最大额度
    private WalletDebit selectPeriod;//选择的还款期限
    private boolean isCanCheckContract;
    private String checkContractMsg = "";


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        setCurrentTitle("借贷信息");
        walletDebit = (WalletDebit) getIntent().getSerializableExtra("walletDebit");
        tvProType.setText(walletDebit.getCoin().toUpperCase());
        initListeners();
    }

    private void initListeners() {

        etNum.addTextChangedListener(new TextWatcher() {
            boolean deleteLastChar;// 是否需要删除末尾

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.toString().contains(".")) {
                    // 如果点后面有超过6位数值,则删掉最后一位
                    int length = s.length() - s.toString().lastIndexOf(".");
                    // 说明后面有6位数值
                    deleteLastChar = length >= 10;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    isCanCheckContract = false;
                    checkContractMsg = "最小起贷金额为" + walletDebit.getMin_amount();
                    etRepaymentTime.setText("");
                    tvRepaymentInterest.setText("");
                    return;
                }
                if (deleteLastChar) {
                    // 设置新的截取的字符串
                    etNum.setText(s.toString().substring(0, s.toString().length() - 1));
                    // 光标强制到末尾
                    etNum.setSelection(etNum.getText().length());
                    KProgressHUD.create(mContext)
                            .setCustomView(mContext, R.drawable.tips_error)
                            .setLabel(getString(R.string.tmtrade_only_eight))
                            .show().setDuration(1500);
                }


                // 以小数点开头，前面自动加上 "0"
                if (s.toString().startsWith(".")) {
                    etNum.setText("0" + s);
                    etNum.setSelection(etNum.getText().length());
                }
                if (s.toString().startsWith("0") && (s.toString().length() > 1) && !s.toString().startsWith("0.")) {
                    etNum.setText(s.toString().substring(1));
                    etNum.setSelection(etNum.getText().length());
                }

                if (new BigDecimal(etNum.getText().toString()).compareTo(new BigDecimal(maxAmount)) > 0) {
                    etNum.setText(StringUtil.subZeroAndDot(maxAmount));
                    etNum.setSelection(etNum.getText().toString().length());
                }

                mHandler.removeCallbacks(mRunnable);
                //1.5秒没有输入认为输入完毕
                mHandler.postDelayed(mRunnable, 1500);

            }
        });

    }

    private static final int EDIT_OK = 0x001;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (EDIT_OK == msg.what) {
                if (StringUtil.viewGetTextIsEmpty(etNum)){
                    return;
                }
                if (new BigDecimal(etNum.getText().toString().trim()).compareTo(new BigDecimal(walletDebit.getMin_amount())) < 0) {
                    isCanCheckContract = false;
                    checkContractMsg = "最小起贷金额为" + walletDebit.getMin_amount();
                    etRepaymentTime.setText("");
                    tvRepaymentInterest.setText("");
                    KProgressHUD.create(mContext)
                            .setCustomView(mContext, R.drawable.tips_error)
                            .setLabel(checkContractMsg)
                            .show().setDuration(1500);
                } else {
                    getRepaymentSchedules();
                }
            }

        }
    };

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {

            mHandler.sendEmptyMessage(EDIT_OK);
        }
    };


    @Override
    protected void initData() {
        getDebitCredit();
        getPurposeList();
        getPeriodsList();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_apply_wallet_debit;
    }


    CommonSelectDialog selectPurposeDialog;

    @OnClick(R2.id.rl_select_purpose_type)
    void selectPurposeType() {
        if (selectPurposeDialog == null) {
            selectPurposeDialog = new CommonSelectDialog(mContext, "使用用途", purposeList, "");
        }
        selectPurposeDialog.setOnSelectListener(new CommonSelectDialog.OnSelectListener() {
            @Override
            public void onSelectItem(String item, int position) {
                tvPurposeType.setText(item);
            }
        });
        selectPurposeDialog.show();
    }

    CommonSelectDialog selectPeriodDialog;

    @OnClick(R2.id.rl_select_period_type)
    void selectPeriodType() {
        if (selectPeriodDialog == null) {
            selectPeriodDialog = new CommonSelectDialog(mContext, "借贷时间", periodsTimeList, "选择任一期限都可提前还款");
        }
        selectPeriodDialog.setOnSelectListener(new CommonSelectDialog.OnSelectListener() {
            @Override
            public void onSelectItem(String item, int position) {
                tvPeriodType.setText(item);
                period_id = periods.get(position).getId();
                selectPeriod = periods.get(position);
                getRepaymentSchedules();
            }
        });
        selectPeriodDialog.show();
    }


    @OnClick(R2.id.rl_select_repayment_type)
    void checkRepaySchdules() {
        if (TextUtils.isEmpty(etNum.getText().toString().trim())) {
            ToastUtil.showToast("请输入借款金额");
            return;
        }
        if ((new BigDecimal(etNum.getText().toString().trim()).compareTo(BigDecimal.ZERO)<=0)||new BigDecimal(etNum.getText().toString().trim()).compareTo(new BigDecimal(walletDebit.getMin_amount())) < 0) {
            ToastUtil.showToast("最小起贷金额为" + walletDebit.getMin_amount());
            return;
        }
        if (TextUtils.isEmpty(period_id)) {
            ToastUtil.showToast("请选择借款时间");
            return;
        }


        if (mData.isEmpty()) {
            return;
        }
        Intent intent = new Intent(mContext, WalletRepaymentScheduleActivity.class);
        intent.putExtra("walletDebit", walletDebit);
        intent.putExtra("repaymentList", (Serializable) mData);
        intent.putExtra("selectPeriod", selectPeriod);
        mContext.startActivity(intent);

    }


    private void getDebitCredit() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", walletDebit.getCoin());
        mPresenter.getDebitCredit(map);
    }

    private void getPurposeList() {
        mPresenter.getPurposeList();
    }

    private void getPeriodStrings() {
        if (!periods.isEmpty()) {
            for (WalletDebit item : periods) {
                periodsTimeList.add(item.getPeriod() + item.getPeriodUnitStr());
            }
        }
    }

    private void getPeriodsList() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("coin", walletDebit.getCoin());
        mPresenter.getDebitPeriodsSuccess(map);
    }

    private void getRepaymentSchedules() {
        if (StringUtil.viewGetTextIsEmpty(etNum) || TextUtils.isEmpty(period_id)) {
            return;
        }
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("period_id", period_id);
        map.put("amount", StringUtil.viewGetText(etNum));
        mPresenter.getRepaymentScheduleList(map);
    }

    /**
     * 额度
     *
     * @param data
     */
    @Override
    public void onGetDebitCredit(String data) {
        tvMaxAmount.setText("最多可借：" + StringUtil.subZeroAndDot(data));
        maxAmount = data;
    }

    /**
     * 还款计划
     *
     * @param data
     */
    @Override
    public void onGetRepaymentScheduleListSuccess(List<WalletRepayment> data) {
        isCanCheckContract = true;
        mData.clear();
        if (data != null) {
            mData.addAll(data);
        }
        if (!mData.isEmpty()) {
            BigDecimal totalInterest = BigDecimal.ZERO;//总利息
            for (WalletRepayment repayment : data) {
                totalInterest = totalInterest.add(repayment.getInterests());
            }
            tvRepaymentInterest.setText(StringUtil.subZeroAndDot(String.valueOf(totalInterest)));
            String intDay = mData.get(0).getRepay_date().substring(mData.get(0).getRepay_date().lastIndexOf("-") + 1);
            etRepaymentTime.setText(selectPeriod.getPeriod_unit().equals("day") ? mData.get(0).getRepay_date() :
                    "每月" + intDay + "日");
        }
    }

    @Override
    public void onGetRepaymentScheduleListFailed(String errMsg) {
        isCanCheckContract = false;
        checkContractMsg = errMsg;
        etRepaymentTime.setText("");
        tvRepaymentInterest.setText("");

    }

    /**
     * 申请借贷
     *
     * @param data
     */
    @Override
    public void onApplyDebitSuccessed(String data) {
        Intent intent = new Intent(mContext, WalletDebitApplySuccessActivity.class);
        intent.putExtra("walletDebit", walletDebit);
        mContext.startActivity(intent);
        finish();
    }


    /**
     * 期限
     *
     * @param data
     */
    @Override
    public void onGetDebitPeriodsSuccess(List<WalletDebit> data) {
        if (data != null) {
            periods.addAll(data);
        }
        getPeriodStrings();
    }


    /**
     * 用途
     *
     * @param data
     */
    @Override
    public void onGetPurposeList(List<String> data) {
        purposeList.clear();
        purposeList.addAll(data);
    }


    @Override
    public void onGetDebitPeriodsFailed() {

    }

    @OnClick(R2.id.et_repayment_time)
    void repaymentRuleInfo() {
        //还款日期规则
        showRemindDiaLog();
    }

    private RepaymentTimeRuleDialog wordsRemindDialog;

    private void showRemindDiaLog() {
        wordsRemindDialog = new RepaymentTimeRuleDialog(mContext, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wordsRemindDialog.close();
            }
        });
        wordsRemindDialog.show();
    }

    @OnClick(R2.id.tv_user_protocol)
    void checkProtocol() {
        //合同
        if (TextUtils.isEmpty(period_id) || TextUtils.isEmpty(etNum.getText().toString().trim())) {
            ToastUtil.showToast("请先填写完整信息");
            return;
        }
        if (!isCanCheckContract) {
            ToastUtil.showToast(checkContractMsg);
            return;
        } else {
            Intent intent = new Intent(mContext, DebitContractActivity.class);
            intent.putExtra("periodId", period_id);
            intent.putExtra("amount", etNum.getText().toString());
            mContext.startActivity(intent);
        }

    }


    @OnClick(R2.id.tv_confirm)
    void onConfirm() {
        if (StringUtil.viewGetTextIsEmpty(etNum)) {
            ToastUtil.showToast(etNum.getmHint().toString());
            return;
        }

        if ((new BigDecimal(etNum.getText().toString().trim()).compareTo(BigDecimal.ZERO)<=0)||new BigDecimal(etNum.getText().toString().trim()).compareTo(new BigDecimal(walletDebit.getMin_amount())) < 0) {
            ToastUtil.showToast("最小起贷金额为" + walletDebit.getMin_amount());
            return;
        }


        if (TextUtils.isEmpty(tvPurposeType.getText().toString())) {
            ToastUtil.showToast("请选择借贷用途");
            return;
        }

        if (TextUtils.isEmpty(tvPeriodType.getText().toString())) {
            ToastUtil.showToast("请选择借贷时间");
            return;
        }


        if (!cbProtocol.isChecked()) {
            ToastUtil.showToast("请同意消费贷款合同");
            return;
        }

        confirmDebit();
    }

    private void confirmDebit() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put(LibConstant.TOKEN, SPUtil.getString(LibConstant.TOKEN));
        map.put("period_id", period_id);
        map.put("amount", StringUtil.viewGetText(etNum));
        map.put("purpose", tvPurposeType.getText().toString().trim());
        mPresenter.applyDebit(map);
    }


}
